package com.itheima.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.dto.AddCategoryDto;
import com.itheima.dto.ModifyCategoryDto;
import com.itheima.pojo.Category;
import com.itheima.service.CategoryService;
import com.itheima.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public Result addCategory(@RequestBody AddCategoryDto dto) {
        boolean res = categoryService.AddCategory(dto);
        Result result = new Result();
        if (res) {
            result.setCode(1);
            result.setMsg("添加成功");
        } else {
            result.setCode(0);
            result.setMsg("添加失败,'分类名'已存在");
        }
        return result;
    }

    @PutMapping
    public Result modifyCategory(@RequestBody ModifyCategoryDto dto) {
        boolean res = categoryService.modifyCategory(dto);
        Result result = new Result();
        if (res) {
            result.setCode(1);
            result.setData("修改分类信息成功");
        } else {
            result.setCode(0);
            result.setMsg("修改失败");
        }
        return result;
    }

    @DeleteMapping
    public Result delCategory(String id) {
        boolean res = categoryService.delById(id);
        Result result = new Result();
        if (res) {
            result.setCode(1);
            result.setMsg("删除成功");
        } else {
            result.setCode(0);
            result.setMsg("删除失败");
        }
        return result;
    }

    @GetMapping("/list")
    public Result getCagegory() {
        List<Category> category = categoryService.getCategory();
        Result result = new Result();
        result.setCode(1);
        result.setData(category);
        return result;
    }

    @GetMapping("/page")
    public Result getCagegory(@RequestParam(value = "page", defaultValue = "1") Integer page, @RequestParam(value = "pageSize", defaultValue = "10") Integer pagesize) {
        Page<Category> categoryPage = categoryService.getCategoryPage(page, pagesize);
        Result result = new Result();
        result.setCode(1);
        result.setData(categoryPage);
        return result;
    }
}

